package hub

import (
	"errors"
	"fmt"
	"strconv"
	"work-chess/chess"
	"work-chess/service"
)

func (conn *Connection) handleReady() (msgRes string, tag string) {
	if conn.Role == "red" {
		conn.RedReady = 1
		msgRes = "红方已经准备好了"
		tag = "all"
		if conn.ReadyIf() {
			conn.MsgChan <- &Message{
				UserName: conn.User,
				Type:     "system",
				Context:  "可以开下了",
			}
		}
	} else if conn.Role == "black" {
		conn.BlackReady = 1
		msgRes = "黑方已经准备好了"
		tag = "all"
		if conn.ReadyIf() {
			conn.MsgChan <- &Message{
				UserName: conn.User,
				Type:     "system",
				Context:  "可以开下了",
			}
		}
	} else {
		msgRes = "你不是红黑方"
	}
	return
}

// msg已经是()()
func (conn *Connection) handleChess(msg string) (msgRes string, tag string) {
	var err error
	if conn.WhoTurn() != conn.Role {
		tag = "p"
		msgRes = "不是你的回合"
	} else if conn.RedReady != 1 || conn.BlackReady != 1 {
		tag = "p"
		msgRes = "有选手为准备好"
	} else {
		msgRes, err = conn.Chessboard.MovePiece(msg, conn.Role)
		fmt.Println("msgRes", msgRes)
		if err != nil {
			msgRes = fmt.Sprintf("%s %s", msgRes, err)
			if err == errors.New("red胜利") || err == errors.New("black胜利") {
				fmt.Println("游戏结束")
				tag = "all"
				conn.Chessboard = chess.NewGame()
			}
		} else {
			tag = "all"
			conn.Follow(msg)
			conn.Turn++
		}
	}
	return msgRes, tag
}

func (conn *Connection) handleWithdraw(tag string) (msgRes string) {
	if !conn.ReadyIf() {
		return "别乱搞啊"
	}
	if conn.WhoTurn() == conn.Role {
		return "哦豁，对面已经下了"
	}
	if tag == "please" {
		conn.tag = 1
		msgRes = conn.Role + "方申请悔棋"
	} else if tag == "no" {
		conn.tag = 0
		msgRes = "对方拒绝了悔棋"
	} else if tag == "yes" {
		conn.mu.Lock()
		defer conn.mu.Unlock()
		steps := service.Range("room" + strconv.Itoa(conn.GroupId))
		for i := 0; i < len(steps)-1; i++ {
			conn.Chessboard = chess.NewGame()
			conn.handleChess(steps[i])
		}
		service.RedisVal("room" + strconv.Itoa(conn.GroupId))
		conn.tag = 0
	} else {
		msgRes = "err withdraw req"
	}

	return "handleWithdraw succ"
}

//Follow 实现redis实时备份
func (conn *Connection) Follow(step string) {
	service.LPush("room"+strconv.Itoa(conn.GroupId), step)
}

func (conn *Connection) ChangeReady() {
	for k := range conn.Group.ConnectMap {
		if k == conn {
			if conn.Role == "red" {
				conn.Group.RedReady = 0
			}
		}
	}
}
